var geocoder = null;
var map = null;
var bounds = null;
var jQT = null;

var arrayDeptMarkers = [];
var arrayArrMarkers = [];
var markers = [];

var divId = null;

function initialize() {
    /*init geocoding service*/
    geocoder = new google.maps.Geocoder();

    /*Init gmap*/
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    /*bind btn evt for coding address*/
    $("#ity input[type=button]").bind("click", function(event) {
        processAddress(event);
    });

    jQT = new $.jQTouch({
    });

    $('#map_canvas').height($('#mapper').height() - 400);
/*
    $('#map_canvas').height(
            $('#mapper').height() -
                    $('#mapper .toolbar').outerHeight() -
                    $('#marker-nav').outerHeight()
            );
*/
}

function fitsMarkersOnMap() {
    bounds = new google.maps.LatLngBounds();
    for (i in arrayDeptMarkers) {
        bounds.extend(arrayDeptMarkers[i].position);
    }
    for (i in arrayArrMarkers) {
        bounds.extend(arrayArrMarkers[i].position);
    }
    map.fitBounds(bounds);
}

function codeAddress(addr, addrType) {

    geocoder.geocode({ 'address': addr}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            if (addrType == 'dept') {
                markers = arrayDeptMarkers;
                /*select div for showing links*/
                divId = $('#ity_dept_show');
            } else {
                markers = arrayArrMarkers;
                /*select div for showing links*/
                divId = $('#ity_arr_show');
            }

            divId.empty();
            clearMarkers();

            var ul = $('<ul></ul>');

            for (i = 0; i < results.length; i++) {
                /*salvo i markers per poterli togliere dalla mappa successivamnte*/
                addMarker(results[i].geometry.location, results[i].formatted_address);
            }

            var firstMarker = markers.length > 0 ? markers[0] : null;

            // sort the markers
            sortMarkers();

            // if we have at least one marker in the list, then
            // initialize the first marker
            if (firstMarker) {
                activateMarker(firstMarker);
            }
            /*set map bounds*/
            fitsMarkersOnMap();

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });

}

/*search address, display marks on map*/
function processAddress(firedEvent) {
    var btName = $(firedEvent.target).attr("name");
    var addrType = "";
    if (btName.indexOf("dept", 0) != -1) {
        addrType = "dept";
    } else if (btName.indexOf("arr", 0) != -1) {
        addrType = "arr";
    }

    var addressInput = $('input[type="text"][name$="' + btName.concat(":val") + '"]');

    codeAddress($(addressInput).val(), addrType);

    showScreen('mapper');
}

function activateMarker(marker) {
    // iterate through the markers and set to the inactive image
    for (var ii = 0; ii < markers.length; ii++) {
        markers[ii].setIcon('img/pin-inactive.png');
    } // for

    // update the specified marker's icon to the active image
    marker.setIcon('img/pin-active.png');

    // update the navbar title using jQuery
    $('#marker-nav .marker-title')
            .html(marker.getTitle())
            .removeClass('has-detail')
            .unbind('click');

    $('#marker-nav .marker-title')
            .addClass('has-detail')
            .click(function() {
        var link = $('<a></a>', {href:'#'}).append(marker.getTitle());
        link.data('position', marker.position);
        var li = $('<li></li>').append(link);
        var ul = $('<ul></ul>').append(li);
        $(divId).append(ul);
        showScreen('ity');
    });
    // update the marker navigation controls
    updateMarkerNav(getMarkerIndex(marker));
} // activateMarker

function addMarker(position, title) {
    // create a new marker to and display it on the map
    var marker = new google.maps.Marker({
        position: position,
        map: map,
        title: title,
        icon: 'img/pin-inactive.png'
    });

    // add the marker to the array of markers
    markers.push(marker);

    // capture touch click events for the created marker
    google.maps.event.addListener(marker, 'click', function() {
        // activate the clicked marker
        activateMarker(marker);
    });
} // addMarker

function clearMarkers() {
    for (var ii = 0; ii < markers.length; ii++) {
        markers[ii].setMap(null);
    } // for

//    markers = [];
} // clearMarkers

function getMarkerIndex(marker) {
    for (var ii = 0; ii < markers.length; ii++) {
        if (markers[ii] === marker) {
            return ii;
        } // if
    } // for

    return -1;
} // getMarkerIndex


function updateMarkerNav(markerIndex) {

    // find the marker nav element
    var markerNav = $('#marker-nav');

    // reset the disabled state for the images and unbind click events
    markerNav.find('img')
            .addClass('disabled')
            .unbind('click');

    // if we have more markers at the end of the array, then update
    // the marker state
    if (markerIndex < markers.length - 1) {
        markerNav.find('img.right')
                .removeClass('disabled')
                .click(function() {
            activateMarker(markers[markerIndex + 1]);
        });
    } // if

    if (markerIndex > 0) {
        markerNav.find('img.left')
                .removeClass('disabled')
                .click(function() {
            activateMarker(markers[markerIndex - 1]);
        });
    } // if
} // updateMarkerNav

function showScreen(screenId) {
    jQT.goTo('#' + screenId);
} // showScreen

function sortMarkers() {
    // sort the markers from top to bottom, left to right
    // remembering that latitudes are less the further south we go
    markers.sort(function(markerA, markerB) {
        // get the position of marker A and the position of marker B
        var posA = markerA.getPosition();
        var posB = markerB.getPosition();

        var result = posB.lat() - posA.lat();
        if (result === 0) {
            result = posA.lng() - posB.lng();
        } // if

        return result;
    });
} // sortMarkers